#include "general.h"
#include "liquiddeco.h"
#include <zlib.h>

#include <buola/gui/cimagematrix.h>

namespace buola { namespace gui {

img::CPicture CCairoDecoHelper::LoadImage(int i)
{
    SCairoImage &lI=sCairoImages[i];
    uLongf lRealLen=(((uint32_t)lI.mData[0])<<24)+(((uint32_t)lI.mData[1])<<16)+
                    (((uint32_t)lI.mData[2])<<8)+((uint32_t)lI.mData[3]);

    unsigned char *lBuffer=(unsigned char*)alloc_mem(lRealLen);

    uncompress(lBuffer,&lRealLen,lI.mData+4,lI.mLength-4);

    return clone(img::view_rgba8(lBuffer,CSize_i(lI.w,lI.h)));
}

img::CPicture CCairoDecoHelper::LoadImage(const std::wstring &pName)
{
    for(int i=0;sCairoImages[i].mData;i++)
    {
        if(pName==sCairoImages[i].mName)
            return LoadImage(i);
    }

    throw XNotFound(I18N("Can't find liquid image"));
}

img::CImage_rgba8 CCairoDecoHelper::LoadImage2(int i)
{
    SCairoImage &lI=sCairoImages[i];
    uLongf lRealLen=(((uint32_t)lI.mData[0])<<24)+(((uint32_t)lI.mData[1])<<16)+
                    (((uint32_t)lI.mData[2])<<8)+((uint32_t)lI.mData[3]);

    unsigned char *lBuffer=(unsigned char*)alloc_mem(lRealLen);

    uncompress(lBuffer,&lRealLen,lI.mData+4,lI.mLength-4);

    return clone(img::view_rgba8(lBuffer,CSize_i(lI.w,lI.h)));
}

img::CImage_rgba8 CCairoDecoHelper::LoadImage2(const std::wstring &pName)
{
    for(int i=0;sCairoImages[i].mData;i++)
    {
        if(pName==sCairoImages[i].mName)
            return LoadImage2(i);
    }

    throw XNotFound(I18N("Can't find liquid image"));
}

CImageMatrix *CCairoDecoHelper::LoadMatrix(const std::wstring &pName)
{
    for(int i=0;sCairoMatrices[i].mImage>=0;i++)
    {
        SCairoMatrix &lM=sCairoMatrices[i];
        if(pName==sCairoImages[lM.mImage].mName)
        {
            img::CImage_rgba8 lImage=LoadImage2(lM.mImage);
            CImageMatrix *lMatrix=new CImageMatrix;
            lMatrix->Create(std::move(lImage),CRect_d(CPoint_d(lM.x,lM.y),CSize_d(lM.w,lM.h)));
            return lMatrix;
        }
    }

    throw XNotFound(I18N("Can't find liquid matrix"));
}

void CCairoDecoHelper::InitMatrixPool(const std::wstring &pName,
                    CColorMatrixPool &pPool,bool pInvert)
{
    for(int i=0;sCairoMatrices[i].mImage>=0;i++)
    {
        SCairoMatrix &lM=sCairoMatrices[i];
        if(pName==sCairoImages[lM.mImage].mName)
        {
            img::CImage_rgba8 lImage=LoadImage2(lM.mImage);
            if(pInvert)
            {
                ///\todo
                //lImage->FlipHorz();
                //lImage->FlipVert();
            }
            pPool.Init(std::move(lImage),CRect_d(CPoint_d(lM.x,lM.y),CSize_d(lM.w,lM.h)));
            break;
        }
    }
}

/*namespace gui*/ } /*namespace buola*/ }
